<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    :okButtonProps="{ props: {disabled: disableSubmit} }"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="移库单id"
          :hidden="hiding"
          hasFeedback>
          <a-input placeholder="请输入移库单id" v-decorator="['moveId', {'initialValue':this.mainId}]" />
        </a-form-item>


        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="移库内容">
          <div style="width: 100%">
            <a-card v-for="(detail,detailIndex) in detailOptions" size="small" :style="{ marginTop: '10px' }">
              <a-form layout="inline" style="width: 100%;">
                <a-form-item
                  layout="inline">
                  <span class="ant-input-span" >商品{{detailIndex+1}}：  </span>
                  <a-auto-complete
                    v-model="detail.productSn"
                    :data-source="productSnDataSource"
                    style="width: 160px"
                    placeholder="货号"
                    :filter-option="filterOption"
                  />
                </a-form-item>
                <a-form-item
                  layout="inline">
                  <span class="ant-input-span" >数量：  </span>
                  <a-input-number  v-model="detail.productQty"/>
                </a-form-item>
                <a-form-item
                  layout="inline">
                  <span class="ant-input-span" >来源类型：  </span>
                  <j-dict-select-tag v-model="detail.fromStockType" placeholder="来源类型" :type="'radioButton'" dictCode="stock_type_move"/>
                </a-form-item>
                <a-form-item
                  layout="inline">
                  <span class="ant-input-span" >目的类型：  </span>
                  <j-dict-select-tag v-model="detail.toStockType" placeholder="目的类型" :type="'radioButton'" dictCode="stock_type_move"/>
                </a-form-item>
                <a-form-item
                  layout="inline">
                  <a href="#" v-if="detailOptions.length > 1" @click="handleDelDetailClick(detailIndex)">删除</a>
                </a-form-item>
              </a-form>
            </a-card>
            <a-button style="marginTop: 6px" @click="handleAddDetailClick">
              添加商品
            </a-button>
          </div>
        </a-form-item>

      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
  import {httpAction, getAction} from '@/api/manage'
  import pick from 'lodash.pick'
  import moment from 'moment'
  import JDate from '@/components/jeecg/JDate'

  export default {
    components: {
      JDate
    },
    name: 'StmMoveItemAddModal',
    data() {
      return {
        title: '操作',
        visible: false,
        model: {},
        labelCol: {
          xs: {span: 24},
          sm: {span: 5}
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16}
        },
        moment,
        format: 'YYYY-MM-DD HH:mm:ss',
        disableSubmit: false,
        detailOptions: [],
        productSnDataSource: [],
        mainId: '',
        hiding: false,
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules: {
        },
        url: {
          add: '/stm/stmMove/addStmMoveItem',
          edit: '/stm/stmMove/editStmMoveItem',
          queryList: "/pms/pmsProduct/queryList",
        }
      }
    },
    created() {
    },
    methods: {
      add(mainId) {
        if (mainId) {
          this.edit({mainId}, '')
        } else {
          this.$message.warning('请选择一条数据')
        }
      },
      detail(record) {
        this.edit(record, 'd')
      },
      edit(record, v) {
        if (v == 'e') {
          this.hiding = false;
          this.disableSubmit = false;
        } else if (v == 'd') {
          this.hiding = false;
          this.disableSubmit = true;
        } else {
          this.hiding = true;
          this.disableSubmit = false;
        }
        this.detailOptions = [];
        this.form.resetFields();
        this.mainId = record.mainId;
        this.model = Object.assign({}, record);
        this.getProduct();
        if(this.detailOptions.length === 0) {
          this.detailOptions.push({ productSn: '', productQty: 1, fromStockType: '', toStockType: '' })
        }
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'moveId' ))
          // 时间格式化
        })
      },
      close() {
        this.$emit('close');
        this.visible = false;
      },
      handleAddDetailClick (e) {
        this.detailOptions.push({ productSn: '', productQty: 1, fromStockType: '', toStockType: '' })
      },
      handleDelDetailClick (e) {
        this.detailOptions.splice(e, 1)
      },
      getProduct(){
        getAction(this.url.queryList).then(res=>{
          if(res.success){
            console.log('ProductData => ' + res.result);
            this.productSnDataSource =  [... new Set(res.result.map(data => (data['productSn'])))];
          }else{
            console.log(res.message);
          }
        });
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLocaleLowerCase().indexOf(input.toLocaleLowerCase()) >= 0
        );
      },
      handleOk() {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if (!this.model.id) {
              httpurl += this.url.add;
              method = 'post';
            } else {
              httpurl += this.url.edit;
              method = 'put';
            }
            let formData = Object.assign(this.model, values);
            formData.detailList = this.detailOptions;

            let index1 = formData.detailList.findIndex(item => {
              if ( item.productSn === null  || item.productSn === '' || item.productSn === undefined ) {
                return true;
              }
              if ( item.fromStockType === null  || item.fromStockType === '' || item.fromStockType === undefined ) {
                return true;
              }
              if ( item.toStockType === null  || item.toStockType === '' || item.toStockType === undefined ) {
                return true;
              }
              if ( item.productQty === null  || item.productQty === '' || item.productQty === undefined || item.productQty < 1 ) {
                return true;
              }
              if ( item.fromStockType === item.toStockType ) {
                return true;
              }
            })

            if(index1 !== -1) {
              that.confirmLoading = false;
              this.$message.warning('商品内容不符合要求，请检查！');
              return;
            }
            //时间格式化
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('ok');
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
        })
      },
      handleCancel() {
        this.close();
      }
    }
  }
</script>

<style scoped>

</style>
